package org.idtem.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.idtem.utils.constants.Constants;

public class FileUtils {

	/***
	 * Permite eliminar un archivo, si este existe.
	 * @param fullFilePath
	 */
	public static void delete(String fullFilePath){
	    File file = new File(fullFilePath);
	    if (file.exists()){
	    	file.delete();
	    }
	}

	/***
	 * Permite crear un nuevo archivo en la ruta dada y con el contenido pasado por parametro.
	 * @param fullFilePath
	 * @param content
	 * @throws IOException
	 */
	public static void createFile(String fullFilePath, String content) throws IOException {
    	FileWriter fw = new FileWriter(fullFilePath);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter salida = new PrintWriter(bw);
        salida.print(content);
        salida.close();
        bw.close();
        fw.close();
	}

	// se utiliza en el read file.
    public static ArrayList<String> loadFile(String fileName)
    {
        if ((fileName == null) || (fileName == ""))
            throw new IllegalArgumentException();
        
        String line;
        ArrayList<String> file = new ArrayList<String>();
        try
        {    
        	FileReader fr = new FileReader(fileName);
            BufferedReader in = new BufferedReader(fr);
            if (!in.ready()) throw new IOException();
            while ((line = in.readLine()) != null)
            { 
                file.add(line);
            }
            in.close();            
        }
        catch (IOException e)
        {
            System.out.println(e);
            return null;
        }
        return file;
    }

	public static String readFile(String filename) {
		String fultext = "";
		ArrayList<String> lineas = loadFile(filename);
		for (String linea : lineas) {
			fultext += linea + Constants.Common.NEWLINE;
		}
		return fultext;
	}
}
